package com.control.qct.businesssteward.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.control.qct.businesssteward.R;
import com.control.qct.businesssteward.activity.GoodsActivity;
import com.control.qct.businesssteward.activity.GoodsTypeActivity;
import com.control.qct.businesssteward.adapter.GoodsAdapter;
import com.control.qct.businesssteward.base.BaseBean;
import com.control.qct.businesssteward.base.BaseFragment;
import com.control.qct.businesssteward.model.GoodsModel;
import com.control.qct.businesssteward.httputils.HttpUtils;
import com.control.qct.businesssteward.utils.CustomCodeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/12/16 0016.
 */

public class GoodsFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener, HttpUtils
        .IHttpResult, GoodsDetailFragment.IChangeGoodsStatus, CustomCodeUtils.ICallbackListener, SwipeRefreshLayout
        .OnRefreshListener {
    @BindView(R.id.iv_goods_style)
    ImageView mIvGoodsStyle;//商品显示样式
    @BindView(R.id.et_barcode)
    EditText mEtBarcode;//条形码输入框
    @BindView(R.id.iv_sure)
    ImageView mIvSure;//确认条形码
    @BindView(R.id.iv_scan)
    ImageView mIvScan;//扫描条形码
    @BindView(R.id.rv_goods)
    RecyclerView mRvGoods;//商品列表
    @BindView(R.id.srl_refresh_goods)
    SwipeRefreshLayout mSrlRefreshGoods;

    private GoodsActivity mGoodsActivity;
    private List<GoodsModel.DatasBean> mGoodsBeanList = new ArrayList<>();
    private GoodsAdapter mGoodsAdapter;

    private Map<String, String> mParams;
    private String mCategorySn = "";
    private String mBarcode = "";
    private int mPageNum = 1;
    private final static int GOODS_TYPE = 0x001;
    private boolean isFirst = true;
    private String mSelectType = "";
    private boolean mIsRefreshing;//判断是否处于下拉刷新

    @Override
    protected View initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        return inflater.inflate(R.layout.fragment_goods, container, false);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mGoodsActivity = (GoodsActivity) context;
    }

    @Override
    protected void initView(View view) {
        mGoodsActivity.setTitle("商品");
        mGoodsActivity.setLeftIcon(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mGoodsActivity.finish();
            }
        });
        mSrlRefreshGoods.setOnRefreshListener(this);//设置下拉刷新
        mSrlRefreshGoods.setColorSchemeColors(Color.parseColor("#05C1AB"), Color.parseColor("#FF66B7"), Color
                .parseColor("#FFBB43"));//设置下拉进度条主题颜色

        mGoodsActivity.setRightIcon("新增", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isFirst = false;
                mGoodsActivity.replaceFragment(R.id.fl_content, new GoodsDetailFragment(1, GoodsFragment.this), true);
            }
        });
        if (isFirst) {//判断是否首次进入
            getGoodsList(mCategorySn, "", mPageNum, true);
        }
        mRvGoods.setLayoutManager(new LinearLayoutManager(mGoodsActivity));
        mGoodsAdapter = new GoodsAdapter(mGoodsBeanList);
        mRvGoods.setAdapter(mGoodsAdapter);
        mGoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                isFirst = false;
                mGoodsActivity.replaceFragment(R.id.fl_content, new GoodsDetailFragment(2, ((List<GoodsModel
                        .DatasBean>) adapter.getData()).get(position), GoodsFragment.this), true);
            }
        });
    }

    @OnClick({R.id.iv_goods_style, R.id.iv_sure, R.id.iv_scan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_goods_style://品类
                Bundle bundle = new Bundle();
                bundle.putInt("id", 1);
                bundle.putString("value", mCategorySn);
                bundle.putString("type", mSelectType);
                startActivityForResult(GoodsTypeActivity.class, GOODS_TYPE, bundle);
                break;
            case R.id.iv_sure://确定
                searchBarcode();
                break;
            case R.id.iv_scan://扫描
                CustomCodeUtils.getInstance(mGoodsActivity).startToCaptureActivity(this);
                break;
        }
    }

    /**
     * 扫码搜索商品
     */
    private void searchBarcode() {
        mBarcode = mEtBarcode.getText().toString();
        mPageNum = 1;
        mGoodsBeanList.clear();
        getGoodsList(mCategorySn, mBarcode, mPageNum, true);
    }

    /**
     * 获取商品列表
     *
     * @param categorySn
     * @param barcode
     * @param pageNum
     */
    private void getGoodsList(String categorySn, String barcode, int pageNum, boolean isShow) {
        mParams = new HashMap<>();
        mParams.put("categorySn", categorySn);
        mParams.put("barcode", barcode);
        mParams.put("pageNum", pageNum + "");
        mParams.put("pageSize", "10");
        mNetProtocol.getGoodsList(activity, mParams, isShow, this);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == activity.RESULT_OK) {
            switch (requestCode) {
                case GOODS_TYPE:
                    mCategorySn = data.getStringExtra("typeSN");//返回的选择的品类对应的id
                    mSelectType = data.getStringExtra("type");//返回的选择的品类对应的名称
                    mGoodsBeanList.clear();
                    mPageNum = 1;
                    getGoodsList(mCategorySn, "", mPageNum, true);
                    break;
                default:
                    CustomCodeUtils.getInstance(mGoodsActivity).onCallBackListener(requestCode, data, this);
                    break;
            }
        }
    }

    @Override
    public void onLoadMoreRequested() {
        mPageNum++;
        getGoodsList(mCategorySn, mBarcode, mPageNum, false);
    }

    @Override
    public void onSuccess(BaseBean baseBean) {
        GoodsModel goodsModel = (GoodsModel) baseBean.getData();
        if (mIsRefreshing) {
            mGoodsBeanList.clear();
            mIsRefreshing = false;
            mGoodsAdapter.setEnableLoadMore(true);
        }
        mGoodsBeanList.addAll(goodsModel.getDatas());
        mSrlRefreshGoods.setRefreshing(false);//设置取消刷新
        if (mGoodsAdapter != null) {
            if (mGoodsBeanList.size() == 0) {
                mGoodsAdapter.setEmptyView(R.layout.nothing_search_view);
            }
            if (goodsModel.getDatas().size() > 9) {
                mGoodsAdapter.setOnLoadMoreListener(this, mRvGoods);
                mGoodsAdapter.loadMoreComplete();//加载完成
            } else {
                mGoodsAdapter.loadMoreEnd();//加载结束 没有更多数据,不再去请求网络
            }
            mGoodsAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onFail(BaseBean baseBean) {
        showLongToast(baseBean.getMessage());
    }

    @Override
    public void changeGoodsState(boolean change) {
        if (change) { //如果状态改变  联网刷新
            mGoodsBeanList.clear();
            mPageNum = 1;
            getGoodsList(mCategorySn, mBarcode, mPageNum, true);
        }
    }

    @Override
    public void onCallbackListener(String result) {
        mEtBarcode.setText(result);
        mEtBarcode.setSelection(mEtBarcode.length());
        searchBarcode();
    }

    @Override
    public void onRefresh() {
        mPageNum = 1;
        mIsRefreshing = true;
        mGoodsAdapter.setEnableLoadMore(false);
        getGoodsList(mCategorySn, mBarcode, mPageNum, false);
    }
}
